package com.android.equipment.ui.device
import android.os.Bundle
import com.android.equipment.R
import com.android.equipment.adapter.DeviceDataAdapter
import com.android.equipment.base.BaseActivity
import com.android.equipment.dao.operate.DaoData
import com.android.equipment.databinding.ActivityDeviceDataBinding
import com.gyf.immersionbar.ImmersionBar
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader

class DeviceDataActivity: BaseActivity<ActivityDeviceDataBinding>() {
    val deviceCode by lazy { intent.getStringExtra("deviceCode") }

    private val deviceDataAdapter by lazy { DeviceDataAdapter() }

    private var pageNum = 1
    override fun setLayoutContent() = ActivityDeviceDataBinding.inflate(layoutInflater)

    override fun initView(savedInstanceState: Bundle?) {
        initRecycler()
        initRefresh()

        binding.mTitleBar.leftView.setOnClickListener {
            mSwipeBackHelper.backward()
        }
    }

    override fun initData() {
        binding.refresh.autoRefresh()
    }

    private fun initRecycler(){
        binding.rvData.adapter = deviceDataAdapter
    }

    private fun initRefresh(){
        binding.refresh.setRefreshHeader(ClassicsHeader(mContext))
        binding.refresh.setRefreshFooter(ClassicsFooter(mContext))
        binding.refresh.setOnRefreshListener {
            pageNum = 1
            requestData()
        }.setOnLoadMoreListener {
            requestData()
        }
    }

    private fun requestData(){
        //总条数
        val totalCount = DaoData.getInstance().getDataCountByDeviceCode(deviceCode)
        //总页数
        val totalPages = (totalCount + 10 -1) / 10
        if (pageNum > totalPages){
            binding.refresh.finishLoadMoreWithNoMoreData()
        }else {
            val offset = (pageNum - 1) * 10
            val data = DaoData.getInstance().getDataByDeviceCodeAndPage(deviceCode, offset)
            deviceDataAdapter.addData(data)
            pageNum ++
        }

        binding.refresh.finishRefresh()
        binding.refresh.finishLoadMore()

    }

    override fun setStatusBar() {
        ImmersionBar.with(this)
            .fullScreen(true)
            .statusBarColor(R.color.F8F9FA)
            .statusBarDarkFont(true)
            .titleBar(binding.mTitleBar)
            .init()
    }
}